#!/usr/bin/env bash

# 引入外部脚本
. "${LINUX_TOOLS_DIR}/utils/utils.sh"
for f in ${LINUX_TOOLS_DIR}/scripts/system/*.sh; do
  if [ "$f" != "${LINUX_TOOLS_DIR}/scripts/system/system.sh" ]; then
    source $f
  fi
done

function fixed_ip() {
  clear
  echo_red "===================开始固定IP地址==================="
  local ip=""                   #ip
  local netmask="255.255.255.0" #子网掩码
  local gateway=""              #网关
  local networkCard=""          #网卡

  ip a
  networkCard=$(read_input "请确认要修改的网卡：" ${networkCard})
  ip=$(read_input "请输入固定的IP地址：" ${ip})
  netmask=$(read_input "请输入子网掩码,默认(${netmask})：" ${netmask})
  gateway=$(echo ${ip} | awk -F "." '{print $1"."$2"."$3"."1}')
  gateway=$(read_input "请输入网关地址,默认(${gateway})：" ${gateway})

  local operatingSystem=$(hostnamectl | grep Operating | awk -F : '{print $2}' | sed 's/^[ \t]*//g') # 操作系统

  if [[ "$(echo ${operatingSystem} | grep -i "debian")" != "" ]]; then
    echo_red -e "生成备份文件....."
    cp /etc/network/interfaces /etc/network/interfaces.bak
    sed -i '/'"${networkCard}"'/d' /etc/network/interfaces

    sed -i '$a'"auto ${networkCard}" /etc/network/interfaces
    sed -i '$a'"iface ${networkCard} inet static" /etc/network/interfaces
    sed -i '$a'"address ${ip}" /etc/network/interfaces
    sed -i '$a'"etmask ${netmask}" /etc/network/interfaces
    sed -i '$a'"gateway ${gateway}" /etc/network/interfaces

    systemctl restart network
    if [ $? -eq 0 ]; then
      echo_green "修改成功!"
    else
      systemctl restart networking
      if [ $? -eq 0 ]; then
        echo_green "修改成功!"
      else
        echo_red "修改失败!请检查IP是否已修改,尝试重启系统"
      fi
    fi
  elif [[ "$(echo ${operatingSystem} | grep -i "centos")" != "" ]]; then

    config_add_or_update "BOOTPROTO=static" "/etc/sysconfig/network-scripts/ifcfg-${networkCard}"
    config_add_or_update "IPADDR=${ip}" "/etc/sysconfig/network-scripts/ifcfg-${networkCard}"
    config_add_or_update "NETMASK=${netmask}" "/etc/sysconfig/network-scripts/ifcfg-${networkCard}"
    config_add_or_update "GATEWAY=${gateway}" "/etc/sysconfig/network-scripts/ifcfg-${networkCard}"

    sleep 1
    systemctl restart network
    if [ $? -eq 0 ]; then
      echo_green "修改成功!"
    else
      echo_red "修改失败!请检查IP是否已修改,尝试重启系统"
    fi
  fi
}
# 创建swap交换分区
function create_swap() {
  local path="/swapfile"
  local capacity=2
  local threshold=10

  clear
  echo "===================开始修改swap分区==================="
  echo_red "注:过度使用swap会导致严重的性能下降,生产环境不建议使用"

  echo "1.检查是否存在swap分区"
  local filepath=$(swapon -s | awk 'NR==2 {print $1}')
  if [[ "${filepath}" != "" ]]; then
    swapoff ${filepath} &>/dev/null
    sed -i "${filepath}/d" /etc/fstab
    rm ${filepath} &>/dev/null
  fi

  capacity=$(read_input "请输入大小(默认为 ${capacity}G 单位:G)：" ${capacity})
  threshold=$(read_input "请输入swap使用阈值(默认为 ${threshold})：" ${threshold})

  echo "开始创建swap文件,请等待......"
  local o=$(awk "BEGIN{printf ${capacity}*1024000}")
  dd if=/dev/zero of=${path} bs=1024 count=${o} &>/dev/null
  /sbin/mkswap ${path} &>/dev/null
  /sbin/swapon ${path} &>/dev/null

  echo "挂载并激活分区......"
  chmod -R 0600 ${path} &>/dev/null
  echo "${path} swap swap default 0 0" >>/etc/fstab

  config_add_or_update "vm.swappiness = ${threshold}" /etc/sysctl.conf
  sysctl -p &>/dev/null

  echo -n "swap大小为: "
  echo_green "$(free -h | grep wap: | awk -F " " '{print $2}')"
  echo -n "swap使用阈值为: "
  echo_green "$(cat /proc/sys/vm/swappiness)"
}
function selinux() {
  #判断当前的状态
  local result=$(getenforce)
  if [ "${result}" == "Enforcing" ]; then
    echo -e "INFO $(date +%Y-%m-%d_%H:%M:%S) selinux是开启状态，需要关闭！"
    #临时关闭操作
    setenforce 0 &>/dev/null
    #永久关闭操作
    find_key="SELINUX="
    sed -ri "/^$find_key/c${find_key}disabled" /etc/selinux/config
    result_1=$(getenforce)
    if [ "${result_1}" == "Enforcing" ]; then
      echo -e "INFO $(date +%Y-%m-%d_%H:%M:%S) selinux关闭操作失败，请手台进行操作"
      exit 2
    else
      echo -e "INFO $(date +%Y-%m-%d_%H:%M:%S) selinux关闭成功继续部署"
    fi
  else
    echo -e "INFO $(date +%Y-%m-%d_%H:%M:%S) selinux是关闭状态，无需操作！"
  fi
}

#修改ssh端口号
function update_ssh_port() {
  selinux

  # 去掉 #Port 的注释
  sed -i 's/#Port/Port/' /etc/ssh/sshd_config

  # 读取当前的 SSH 端口号
  current_port=$(grep -E '^ *Port [0-9]+' /etc/ssh/sshd_config | awk '{print $2}')

  # 打印当前的 SSH 端口号
  echo "当前的 SSH 端口号是: $current_port"

  echo "------------------------"

  # 提示用户输入新的 SSH 端口号
  read -p "请输入新的 SSH 端口号: " new_port

  # 备份 SSH 配置文件
  cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

  # 替换 SSH 配置文件中的端口号
  sed -i "s/Port [0-9]\+/Port $new_port/g" /etc/ssh/sshd_config

  # 重启 SSH 服务
  service sshd restart
  restart sshd ssh > /dev/null 2>&1

  echo "检查防火墙 $new_port 端口是否开启"

  ufw allow ${new_port}/tcp &>/dev/null
  firewall-cmd --zone=public --add-port=${new_port}/tcp --permanent &>/dev/null
  firewall-cmd --reload &>/dev/null
  iptables -A INPUT -p tcp --dport ${new_port} -j ACCEPT &>/dev/null
  echo "SSH 端口已修改为: $new_port"
}

function system_main() {
  clear
  echo_line "LINUX_TOOLS"
  echo_menu "1." "系统检查优化"
  echo_menu "2." "系统资源信息"
  echo_menu "3." "固定IP"
  echo_menu "4." "创建swap"
  echo_menu "5." "修改SSH端口"
  echo_menu "0." "返回上一层菜单"
  echo_line "LINUX_TOOLS"

  read -r -p "请输入要安装服务的编号(select)：" input
  case $input in
  1)
    system_init
    break_end
    system_main
    ;;
  2)
    system_info
    break_end
    system_main
    ;;
  3)
    fixed_ip
    break_end
    system_main
    ;;
  4)
    create_swap
    break_end
    system_main
    ;;
  5)
    update_ssh_port
    break_end
    system_main
    ;;
  6)
    selinux
    break_end
    system_main
    ;;
  0)
    main
    ;;
  *)
    clear
    echo_red "请输入正确的编号，ctrl+c退出"
    sleep 1s
    system_main
    ;;
  esac
}
